package com.jyniubi.picture.backend.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jyniubi.picture.backend.annotation.AuthCheck;
import com.jyniubi.picture.backend.common.BaseResponse;
import com.jyniubi.picture.backend.common.DeleteRequest;
import com.jyniubi.picture.backend.common.ResultUtils;
import com.jyniubi.picture.backend.constant.UserConstant;
import com.jyniubi.picture.backend.exception.BusinessException;
import com.jyniubi.picture.backend.exception.ErrorCode;
import com.jyniubi.picture.backend.exception.ThrowUtils;
import com.jyniubi.picture.backend.model.dto.picture.PictureEditRequest;
import com.jyniubi.picture.backend.model.dto.picture.PictureQueryRequest;
import com.jyniubi.picture.backend.model.dto.picture.PictureUpdateRequest;
import com.jyniubi.picture.backend.model.dto.picture.PictureUploadRequest;
import com.jyniubi.picture.backend.model.entity.Picture;
import com.jyniubi.picture.backend.model.entity.User;
import com.jyniubi.picture.backend.model.vo.PictureTagCategory;
import com.jyniubi.picture.backend.model.vo.PictureVO;
import com.jyniubi.picture.backend.service.PictureService;
import com.jyniubi.picture.backend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/picture")
public class PictureController {

    @Resource
    private PictureService pictureService;

    @Resource
    private UserService userService;

    @Resource
    private PictureTagCategory pictureTagCategory;

    /**
     * 上传图片（可重新上传）
     * @param multipartFile
     * @param request
     * @param pictureUploadRequest
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/upload")
    public BaseResponse<PictureVO> uploadPicture(@RequestPart("file") MultipartFile multipartFile, HttpServletRequest request, PictureUploadRequest pictureUploadRequest) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.NOT_FOUND_ERROR);
        User userLogin = userService.getUserLogin(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, userLogin);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 编辑图片信息
     *
     * @param pictureEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        // 校验请求参数
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将实体类和dto类进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 判断是否存在
        Long pictureId = pictureEditRequest.getId();
        Picture oldPicture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验图片参数
        pictureService.validPicture(picture);
        // 把tags由list转换为string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());

        User userLogin = userService.getUserLogin(request);
        // 仅本人和管理员可以进行编辑图片
        if (!oldPicture.getUserId().equals(userLogin.getId()) || !userService.isAdmin(userLogin)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 分页获取图片列表（仅管理员可用）
     *
     * @param pictureQueryRequest
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/list/page")
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        // 当前页数及单页显示数量
        int current = pictureQueryRequest.getCurrent();
        int pageSize = pictureQueryRequest.getPageSize();
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, pageSize), pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片列表(封装类)
     *
     * @param pictureQueryRequest
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 15, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size), pictureService.getQueryWrapper(pictureQueryRequest));
        // 获取封装类
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage));
    }

    /**
     * 根据id获取图片（仅管理员可用）
     *
     * @param id
     * @return
     */
    @GetMapping("/getPictureById")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(picture);
    }

    /**
     * 根据图片id获取图片（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/getPictureVOById")
    public BaseResponse<PictureVO> getPictureVOById(long id) {
        // 请求参数校验
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 根据id查询图片信息
        Picture picture = pictureService.getById(id);
        // 图片不存在，抛出异常
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 查询封装类
        return ResultUtils.success(pictureService.getPictureVO(picture));
    }

    /**
     * 更新图片
     *
     * @param pictureUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest) {
        if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将实体类和DTO类转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        // 图片参数校验
        pictureService.validPicture(picture);
        Long id = pictureUpdateRequest.getId();
        Picture oldPicture = pictureService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 更新图片信息
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 删除图片
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取图片id
        long id = deleteRequest.getId();
        // 判断是否存在
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);

        User userLogin = userService.getUserLogin(request);
        // 仅本人或管理员可删除
        if (!userService.isAdmin(userLogin) && !picture.getUserId().equals(userLogin.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = pictureService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 获取标签和分类
     * @return
     */
    @GetMapping("/tagAndCategory")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        List<String> tagList = pictureTagCategory.getTagList();
        List<String> categoryList = pictureTagCategory.getCategoryList();
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }

}